Box
Rust-like Box for TypeScript
npm i @hazae41/box
Node Package 📦
Features
Current features
- 100% TypeScript and ESM
- No external dependencies
- Similar to Rust
- Can hold data
- Unit-tested
- Uses Result from
@hazae41/result
Usage
The Box<T extends Disposable>
will:
- hold a disposable object
T
- only dispose the object if it still owns it
- no longer own it if the box is moved
import { Box } from "@hazae41/box"
class D {
[Symbol.dispose]() {
console.log("it should only happen once")
}
}
{
using box = new Box(new D())
using box2 = box.move()
}
Rules
- You can't pass a disposable object without wrapping it in a Box
- You can't hold a disposable object without wrapping it in a Box
- You can't hold a Box without owning it and disposing it after
- You can't return a Box without unwrapping it
This means the typical object holding a Box looks like this
import { Box } from "@hazae41/box"
class MyWrapper<T extends Disposable> {
private constructor(
readonly box: Box<T>
) {}
[Symbol.dispose]() {
this.box[Symbol.dispose]()
}
static create<T extends Disposable>(box: Box<T>) {
return new MyWrapper(box.move())
}
use() {
something(this.box)
}
export(): T {
return this.box.unwrap()
}
}